namespace SimpleWebServices.Web.Routing
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Models;

    public sealed class TenantStyleSheetRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData result = null;

            Route route = TenantStyleSheetRoute.GetRoute(httpContext);
            if (null != route)
            {
                result = route.GetRouteData(httpContext);
            }

            return result;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            if (null == requestContext)
            {
                throw new ArgumentNullException("requestContext");
            }

            VirtualPathData result = null;

            Route route = TenantStyleSheetRoute.GetRoute(requestContext.HttpContext);
            if (null != route)
            {
                result = route.GetVirtualPath(requestContext, values);
            }

            return result;
        }

        private static Route GetRoute(HttpContextBase httpContext)
        {
            if (null == httpContext)
            {
                throw new ArgumentNullException("httpContext");
            }

            Route result = null;

            Tenant tenant = Tenant.Current;
            if (null != tenant)
            {
                string path = httpContext.Request.Path;
                foreach (StyleSheet stylesheet in tenant.StyleSheets.Where(x => 0 != x.Imports.Count))
                {
                    if (string.Equals(path, stylesheet.Href, StringComparison.OrdinalIgnoreCase))
                    {
                        result = new Route(path.Substring(1), new MvcRouteHandler())
                        {
                            Defaults = new RouteValueDictionary(new { controller = "TenantStyleSheet", action = "CssRepresentation" }),
                            Constraints = new RouteValueDictionary()
                        };
                        break;
                    }
                }
            }

            return result;
        }
    }
}